<?php
namespace app\admin\controller;

use app\common\model\Voice as VoiceModel;
use app\common\model\VoiceFile;
use app\admin\service\ToolService;

class Voice extends Base
{
    //删除
    public function del()
    {
        if (request()->isAjax()) {
			$id = input('post.id/d');
            $msg = ['code'=>0,'msg'=>'fail'];
            $item = VoiceModel::get($id);
			if(!empty($item)){
                if(!empty($item['src'])){
                    ToolService::delFile($item['src'],1);
                }
                VoiceModel::destroy($id);
                $files = VoiceFile::where(['voice_id' => $id])->select();
                if(!empty($files)){
                    foreach($files as $file){
                        if(!empty($file['path'])){
                            ToolService::delFile($file['path']);
                        }
                        VoiceFile::destroy($file['id']);
                    }
                }
                $msg = ['code'=>1,'msg'=>'ok'];
            }
            return json($msg);
		}
        $this->error('无此操作');
    }

    //排序
    public function sort()
    {
        if(request()->isPost()){
			$id = input('post.id/d');
			$sort = input('post.sort');
            $msg = ['code'=>0,'msg'=>'fail'];
            if($id > 0 && in_array($sort,['up','down'])){
                $item = VoiceModel::get($id);
                if(empty($item)){
                    $msg = ['code'=>0,'msg'=>'无此文章'];
                }else{
                    if($sort == 'up'){
                        $prev = VoiceModel::where("category_id='{$item['category_id']}' and sort  > {$item['sort']}")
                            ->order("sort asc")
                            ->limit(1)
                            ->find();
                        if(!empty($prev)){
                            VoiceModel::where(['id' => $id])->update(['sort' => $prev['sort']]);
                            VoiceModel::where(['id' => $prev['id']])->update(['sort' => $item['sort']]);
                            $msg = ['code' => 1,'msg' => 'ok'];
                        }else{
                            $msg = ['code'=>0,'msg'=>'无须调整排序'];
                        }
                    }elseif($sort == 'down'){
                        $next = VoiceModel::where("category_id='{$item['category_id']}' and sort < {$item['sort']}")
                            ->order("sort desc")
                            ->limit(1)
                            ->find();
                        if(!empty($next)){
                            VoiceModel::where(['id' => $id])->update(['sort' => $next['sort']]);
                            VoiceModel::where(['id' => $next['id']])->update(['sort' => $item['sort']]);
                            $msg = ['code' => 1,'msg' => 'ok'];
                        }else{
                            $msg = ['code'=>0,'msg'=>'无须调整排序'];
                        }
                    }
                }
			}
            return json($msg);
		}
        $this->error('无此操作');
    }

    //编辑
    public function edit()
    {
        if(request()->isPost()){
            $id = input('post.id/d');
            $delList = input('?post.voice_del') ? input('post.voice_del/a') : [];
            $item = [
                'title' => input('post.title'),
                'description' => input('post.description'),
            ];
            $img = input('post.img');
            $voice = VoiceModel::get($id);
            if(!empty($img)){
                if(!empty($voice['src'])){
				    ToolService::delFile($voice['src'],1);
				}
                $item['src'] = $img;
            }
            VoiceModel::where(['id' => $id])->update($item);
            //语音上传
            $files = request()->file();
            $voice_file = input('post.voice/a');
            $voice_edit = input('post.voice_edit/a');
            $do_items = [];
            if (!empty($delList)) { //删除的语音及相关文件
                foreach ($delList as $delID) {
                    $delFile = VoiceFile::get($delID);
                    if (!empty($delFile)) {
                        VoiceFile::destroy($delFile['id']);
                        ToolService::delFile($delFile['path']);
                    }
                }
            }
            if(!empty($files)){
                foreach($files as $k => $file){
                    if(substr($k,0,11) == 'voice_edit_'){   //修改的语音
                        $key = substr($k,11);
                        $v = $voice_edit[$key]??null;
                        if(!empty($v['description']) && !empty($file)){
                            $fileInfo = $file->getInfo();
                            if(($fileInfo['type'] == 'audio/mp3') || ($fileInfo['type'] == 'audio/mpeg')){
                                $info = $file->move(ROOT_PATH.'public'.DS.'uploads');
                                if($info){
                                    $voice_file_old = VoiceFile::get($key);
                                    if(!empty($voice_file_old)){
                                        if(!empty($voice_file_old['path'])){
                                            ToolService::delFile($voice_file_old['path']);
                                        }
                                        $item = [
                                            'voice_id' => $id,
                                            'path' => '/uploads/'.$info->getSaveName(),
                                            'title' => $v['title'],
                                            'description' => $v['description']
                                        ];
                                        VoiceFile::where(['id' => $key])->update($item);
                                    }

                                }
                            }
                        }
                        unset($voice_edit[$key]);
                    }elseif(substr($k,0,6) == 'voice_'){    //新添加语音
                        $key = substr($k,6);
                        $v = $voice_file[$key]??null;
                        if(!empty($v['description']) && !empty($file)){
                            $fileInfo = $file->getInfo();
                            if(($fileInfo['type'] == 'audio/mp3') || ($fileInfo['type'] == 'audio/mpeg')){
                                $info = $file->move(ROOT_PATH.'public'.DS.'uploads');
                                if($info){
                                    $item = [
                                        'voice_id' => $id,
                                        'path' => '/uploads/'.$info->getSaveName(),
                                        'title' => $v['title'],
                                        'description' => $v['description'],
                                    ];
                                    VoiceFile::create($item);
                                }
                            }
                        }
                    }
                }
            }
            if(!empty($voice_edit)){
                foreach($voice_edit as $k => $v){
                    $item = [
                        'title' => $v['title'],
                        'description' => $v['description']
                    ];
                    VoiceFile::where(['id' => $k])->update($item);
                }
            }
			$this->redirect('Content/voice?category_id='.$voice['category_id']);
		}else{
			$id = input('param.id');
			$item = VoiceModel::get($id);
            if(empty($item)){
                $this->error('无此记录');
            }else{
                $files = VoiceFile::where(['voice_id' => $item['id']])->select();
                $this->assign('item',$item);
                $this->assign('files',$files);
                $this->assign('category_id',$item['category_id']);
    			return view();
            }
		}
    }

    //添加
    public function add()
    {
        if(request()->isPost()){
            $category_id = input('post.category_id/d');
            $item = [
                'title' => input('post.title'),
                'description' => input('post.description'),
                'category_id' => $category_id
            ];
            $img = input('post.img');
            if(!empty($img)){
                $item['src'] = $img;
            }
            $voice = VoiceModel::create($item);
            $files = request()->file();
            $voice_file = input('post.voice/a');
            $msg = '';
            if(!empty($files)){
                foreach($files as $k => $file){
                    $key = substr($k,6);
                    $v = $voice_file[$key]??null;
                    if(!empty($v['description']) && !empty($file)){
                        $fileInfo = $file->getInfo();
                        if(($fileInfo['type'] == 'audio/mp3') || ($fileInfo['type'] == 'audio/mpeg')){
                            $info = $file->move(ROOT_PATH.'public'.DS.'uploads');
                            if($info){
                                $item = [
                                    'voice_id' => $voice->id,
                                    'path' => '/uploads/'.$info->getSaveName(),
                                    'title' => $v['title'],
                                    'description' => $v['description'],
                                ];
                                VoiceFile::create($item);
                            }
                        }
                    }
                }
            }
        	$this->redirect('Content/voice?category_id='.$category_id);
        }else{
        	$category_id = input('param.category_id');
        	$this->assign('category_id',$category_id);
        	return view();
    	}
    }
}
